package com.bighero.mq_to_mail.pAndC.utils;

import com.alibaba.fastjson.JSON;
import com.bighero.mq_to_mail.pAndC.bean.WeatherBean;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class Tianqi {


    public WeatherBean getTianqi(String code){
        WeatherBean weatherBean = null;

        String url = "http://t.weather.sojson.com/api/weather/city/" + code;
        //获得http客户端
        CloseableHttpClient client = HttpClientBuilder.create().build();
        //创建get请求
        HttpGet httpGet = new HttpGet(url);
        //响应模型
        CloseableHttpResponse response = null;
        try{
            //有客户端指定get请求
            response = client.execute(httpGet);
            //从响应模型中获取响应体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:"+response.getStatusLine());
            if (responseEntity!=null){
                String resultTianqi = EntityUtils.toString(responseEntity);
                weatherBean = JSON.parseObject(resultTianqi, WeatherBean.class);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                //释放资源
                if(client!=null){
                    client.close();
                }
                if (response!=null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return weatherBean;
    }
}
